package com.ymatou.shop.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.ymatou.shop.R;
import com.ymatou.shop.account.Account;
import com.ymatou.shop.cache.impl.UrlTranslatorImpl;
import com.ymatou.shop.ui.activity.HomeActivity;
import com.ymatou.shop.ui.activity.LoginActivity;

/**
 * Utilities for loading a bitmap from a URL
 * 
 */
public class Utils {

	// private static final String TAG = "test";

	private static final int IO_BUFFER_SIZE = 4 * 1024;

	public static final int LOAD_USERINFO_FROM_NETWORK_SUCCESSED = 5;
	private static final int MAX_PASSWORD_LENGTH = 16;
	private static final int MIN_PASSWORD_LENGTH = 6;

	/**
	 * 
	 * @param url
	 * @return
	 */
	public static synchronized Bitmap loadBitmap(String url) {
		LogUtil.systemErr("bitmap is " + url);
		Bitmap bitmap = null;
		// if (url.indexOf("http://") == -1){
		// url = "http://"+url;
		// }
		if (StringUtil.isEmpty(url)) {
			return bitmap;
		}
		InputStream inputStream = null;
		HttpURLConnection conn = null;
		try {
			URL httpUrl = new URL(url);
			conn = (HttpURLConnection) httpUrl.openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(3000);
			conn.setRequestMethod("GET");
			conn.connect();
			for (int i = 0; i < 3; i++) {
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					inputStream = conn.getInputStream();
					bitmap = BitmapFactory.decodeStream(inputStream);
					if (inputStream != null) {
						inputStream.close();
						inputStream = null;
					}
					if (conn != null) {
						conn.disconnect();
						conn = null;
					}
					return bitmap;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeStream(inputStream);
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}

		return bitmap;

	}



	public static synchronized InputStream getInputStream(String url, InputStream is) {

		if (url.indexOf("http://") == -1) {
			url = "http://" + url;
		}
		HttpURLConnection conn = null;
		try {
			URL httpUrl = new URL(url);
			conn = (HttpURLConnection) httpUrl.openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(1000);
			conn.setRequestMethod("GET");
			conn.connect();
			for (int i = 0; i < 3; i++) {
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					is = conn.getInputStream();
					if (conn != null) {
						conn.disconnect();
						conn = null;
					}
					return is;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return is;
	}

	public static class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}

		@Override
		public long skip(long n) throws IOException {
			long totalBytesSkipped = 0L;
			while (totalBytesSkipped < n) {
				long bytesSkipped = in.skip(n - totalBytesSkipped);
				if (bytesSkipped == 0L) {
					int b = read();
					if (b < 0) {
						break; // we reached EOF
					} else {
						bytesSkipped = 1; // we read one byte
					}
				}
				totalBytesSkipped += bytesSkipped;
			}
			return totalBytesSkipped;
		}
	}

	/**
	 * Closes the specified stream.
	 * 
	 * @param stream The stream to close.
	 */
	public static void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				// YixiaLog.e(TAG, "Could not close stream", e);
			}
		}
	}

	/**
	 * Copy the content of the input stream into the output stream, using a
	 * temporary byte array buffer whose size is defined by
	 * {@link #IO_BUFFER_SIZE}.
	 * 
	 * @param in The input stream to copy from.
	 * @param out The output stream to copy to.
	 * @throws IOException If any error occurs during the copy.
	 */
	public static void copy(InputStream in, OutputStream out) throws IOException {
		byte[] b = new byte[IO_BUFFER_SIZE];
		int read;
		while ((read = in.read(b)) != -1) {
			out.write(b, 0, read);
		}
	}

	public static boolean checkSDCard() {
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}

	public static String translateFileSize(long filesize) {
		if (filesize < 0)
			return "0KB";
		else if (filesize > 1073741824) {
			int s = (int) (100 * filesize / 1073741824);
			return Float.toString(s / 100) + " G";
		} else if (filesize > 1048576) {
			int s = (int) (100 * filesize / 1048576);
			return Float.toString(s / 100) + " M";
		} else {
			int s = (int) (100 * filesize / 1024);
			return Float.toString(s / 100) + " KB";
		}
	}

	public static void freeBitmap(Bitmap b) {
		b.recycle();
	}

	public static String getNumString(String num) {
		DecimalFormat decimalFormat = new DecimalFormat("#,###");
		if (num != null && !"".equalsIgnoreCase(num)) {
			return decimalFormat.format(Long.valueOf(num));
		}
		return null;
	}

	public static String getLength(Integer temp) {
		StringBuffer timeBuffer = new StringBuffer();
		Integer m = temp / 60;
		Integer s = temp % 60;
		if (m < 10) {
			timeBuffer.append("0" + m);
		} else {
			timeBuffer.append(m);
		}
		timeBuffer.append(":");
		if (s < 10) {
			timeBuffer.append("0" + s);
		} else {
			timeBuffer.append(s);
		}
		return timeBuffer.toString();
	}

	/** 获取指定宽度的可见字符 如果有多余 则用'...'表示 */
	public static String getNewVisibleStringAt(int width, Paint paint, String text) {
		try {
			if (text == null || text.length() == 0) {
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder();
			int length = text.length(); // 字符串的长度
			char[] msg_chr = text.toCharArray(); // 存储text的字符形式
			int x = 0;
			int start = 0; // 字符串的开始位置
			int index = 0; // 当前检索字符的索引
			while (index <= length - 1) {
				int tempWidth = (int) paint.measureText(msg_chr, index, 1);
				x += tempWidth;
				if (x > width) {
					String temp1 = new String(msg_chr, start, index - start);
					if (index <= length - 1) {
						// 有省略
						stringBuilder.append(temp1 + "...");
					} else
						stringBuilder.append(temp1);
					return stringBuilder.toString();
				}
				index++;
			}
			// 画最后的子字符串
			index = length;
			if (index > start) {// 如果字符串不为空
				stringBuilder.append(new String(msg_chr, start, index - start));
			}
			return stringBuilder.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * is not empty
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotEmpty(String s) {
		return s != null && s.trim().length() > 0;
	}

	/**
	 * is empty
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isEmpty(String s) {
		return s == null || "".equals(s.trim());
	}

	public static int isExit = 1;

	/**
	 * is EditText empty
	 * 
	 * @param editText
	 * @return
	 */
	public static boolean isNotEmptyForEditText(EditText editText) {
		if (editText != null && editText.getText() != null) {
			String content = editText.getText().toString();
			if (content != null && content.trim().length() > 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 
	 * @param context
	 * @param requestCode
	 */
	public static void startHomeActivity(Context context) {
		context.startActivity(new Intent(context, HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
	}

	public static void startLoginActivity(Context context, String suid) {
		context.startActivity(new Intent(context, LoginActivity.class));
	}
	
	public static void startLoginActivityForResult(Activity activity, int requestCode) {
		activity.startActivityForResult(new Intent(activity, LoginActivity.class), requestCode);
	}


	public static void putSharePreference(Context context, String sharedPreferencesName, String key, String value) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putString(key, value);
		editor.commit();
	}

	public static void putSharePreference(Context context, String sharedPreferencesName, String key, boolean value) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putBoolean(key, value);
		editor.commit();
	}

	public static void putSharePreference(Context context, String sharedPreferencesName, String key, int value) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putInt(key, value);
		editor.commit();
	}

	public static void putSharePreference(Context context, String sharedPreferencesName, String key, long value) {
		if (context == null) {
			return;
		}
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putLong(key, value);
		editor.commit();
	}

	public static String getSharePreference(Context context, String sharedPreferencesName, String key) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		return sharedPreferences.getString(key, "");
	}

	public static long getSharePreferenceLong(Context context, String sharedPreferencesName, String key) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		return sharedPreferences.getLong(key, 0);
	}

	public static int getSharePreferenceInt(Context context, String sharedPreferencesName, String key) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		return sharedPreferences.getInt(key, 0);
	}

	public static int getSharePreferenceInt2(Context context, String sharedPreferencesName, String key) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		return sharedPreferences.getInt(key, 2);
	}

	public static boolean getSharePreferenceBoolean(Context context, String sharedPreferencesName, String key) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		return sharedPreferences.getBoolean(key, false);
	}

	public static boolean getSharePreferenceBooleanDefaultTrue(Context context, String sharedPreferencesName, String key) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		return sharedPreferences.getBoolean(key, true);
	}

	public static void removeSharePreference(Context context, String sharedPreferencesName, String key) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.remove(key);
		editor.commit();
	}

	/**
	 * be careful
	 * 
	 * @param context
	 * @param sharedPreferencesName
	 */
	public static void removeSharePreference(Context context, String sharedPreferencesName) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Activity.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.clear();
		editor.commit();
	}

	public static boolean isExistSdCard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	public static int[] setScreenSize(Integer w, Integer h, Context context) {
		int phoneW = DeviceUtil.getScreenWidth(context);
		int phoneH = DeviceUtil.getScreenHeight(context);

		if (w * phoneH > phoneW * h) {
			phoneH = phoneW * h / w;
		} else if (w * phoneH < phoneW * h) {
			phoneW = phoneH * w / h;
		}

		return new int[] { phoneW, phoneH };
	}

	public static int[] setScreenSize(int w, int h, int phoneW, int phoneH) {
		if (w * phoneH > phoneW * h) {
			phoneH = phoneW * h / w;
		} else if (w * phoneH < phoneW * h) {
			phoneW = phoneH * w / h;
		}
		return new int[] { phoneW, phoneH };
	}

	public static int[] setScreenSize3(int w, int h, int phoneW, int phoneH) {

		if (w * phoneH > phoneW * h) {
			phoneH = phoneW * h / w;
		} else if (w * phoneH < phoneW * h) {
			phoneW = phoneH * w / h;
		}

		return new int[] { phoneW, phoneH };
	}

	public static int[] setScreenSize2(int w, int h, int phoneW, int phoneH) {

		if (w > phoneW) {
			phoneH = phoneW * h / w;
			phoneW = w;
		} else {
			phoneH = phoneW * h / w;
			// phoneW = w;
		}

		return new int[] { phoneW, phoneH };
	}

	public static RelativeLayout.LayoutParams relativeLayoutLayoutParams(Context context) {
		int w = DeviceUtil.getScreenWidth(context);
		int h = w * 266 / 435;
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(w, h);
		return layoutParams;
	}

	public static RelativeLayout.LayoutParams relativeLayoutLayoutParamsToBubble(Context context) {
		int w = DeviceUtil.getScreenWidth(context);
		w = w - 50;
		int h = w * 266 / 435;
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(w, h);
		return layoutParams;
	}

	/**
	 * 获得网络信息
	 * 
	 * @param context
	 * @return
	 */
	public static NetworkInfo networkInfo(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		return networkInfo;
	}

	public static String getContactInfo(Context context) {
		String contacts = "";
		String name = "";
		String contactId = "";
		String phoneSet = "";
		Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		while (cursor.moveToNext()) {
			contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
			name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

			String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

			if (hasPhone.equalsIgnoreCase("1"))
				hasPhone = "true";
			else
				hasPhone = "false";

			phoneSet = "";
			if (Boolean.parseBoolean(hasPhone)) {
				Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
				while (phones.moveToNext()) {
					String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					if ((null != phoneNumber) && (phoneNumber.length() != 0)) {
						phoneSet = phoneSet + phoneNumber;
						phoneSet = phoneSet + "|";
					}
				}
				phoneSet = phoneSet.substring(0, phoneSet.length() - 2);
				phones.close();
			}

			contacts = contacts + phoneSet;
			contacts = contacts + ",";
			contacts = contacts + name;
			contacts = contacts + "\n";
		}

		cursor.close();
		return contacts;
	}

	public static boolean matchSequence(boolean mode, String format, String sequence) {
		boolean result = false;
		Pattern pattern = Pattern.compile(format);
		Matcher matcher = pattern.matcher(sequence);
		if (mode) {
			result = matcher.find();
		} else {
			result = matcher.matches();
		}
		return result;
	}

	public static boolean checkName(String name, boolean isRegisterName) {
		String format = "";
		if (isRegisterName) {
			format = "[\\w]{6,12}";
			if (!Utils.matchSequence(false, format, name)) {
				return false;
			}
			;
		} else {
			// format = "[\\w]{1,12}";
			format = "[\\w]{1,60}(?<!_)";
			if (!Utils.matchSequence(false, format, name)) {
				return false;
			}
			;
		}

		format = "[\\u4E00-\\u9FA5\\uF900-\\uFA2D]";
		if (Utils.matchSequence(true, format, name)) {
			return false;
		}
		;

		return true;
	}

	public static boolean checkPassword(String password) {
		int length = password.length();
		if (length > MAX_PASSWORD_LENGTH || length < MIN_PASSWORD_LENGTH) {
			return false;
		}

		String format = "[\\u4E00-\\u9FA5\\uF900-\\uFA2D]";
		if (Utils.matchSequence(true, format, password)) {
			return false;
		}
		;

		return true;
	}

	/**
	 * InputStream2byte
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static byte[] InputStreamToByte(FileInputStream is) {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// byte[] data = new byte[1024];
		byte[] data2 = null;
		int ch;
		try {
			while ((ch = is.read()) != -1) {
				// byteArrayOutputStream.write(data, 0, ch);
				byteArrayOutputStream.write(ch);
			}
			data2 = byteArrayOutputStream.toByteArray();
			byteArrayOutputStream.close();
		} catch (Exception e) {
		}

		return data2;
	}

	public static boolean checkMail(String mail) {
		String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
		Pattern p = Pattern.compile(strPattern);
		Matcher matcher = p.matcher(mail);
		return matcher.matches();
	}

	public static void notifyUserInfoChange() {
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	/**
	 * transform int to ip string
	 * 
	 * @param i
	 * @return
	 */
	public static String intToIp(int i) {
		return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
	}

	public static String md5(String plain) {
		try {
			MessageDigest m = MessageDigest.getInstance("MD5");
			m.update(plain.getBytes());
			byte[] digest = m.digest();
			BigInteger bigInt = new BigInteger(1, digest);
			String hashtext = bigInt.toString(16);
			while (hashtext.length() < 32)
				hashtext = "0" + hashtext;
			return hashtext;
		} catch (Exception e) {
			return String.valueOf(plain.hashCode());
		}
	}

	public static void copyStream(InputStream is, OutputStream os) throws IOException {
		try {
			final int buffer_size = 8 * 1024;
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} finally {
			closeStream(os);
			closeStream(is);
		}
	}

	public static String getLeftTimeString(long timeLength) {
		if (timeLength > 0) {
			StringBuffer timeBuffer = new StringBuffer();
			long m = timeLength / 60;
			long s = timeLength % 60;
			if (m < 10) {
				timeBuffer.append("0" + m);
			} else {
				timeBuffer.append(m);
			}
			timeBuffer.append("'");
			if (s < 10) {
				timeBuffer.append("0" + s);
			} else {
				timeBuffer.append(s);
			}
			timeBuffer.append("''");
			return timeBuffer.toString();
		}
		return "0'0";

	}

	public static String getFriendlyTimeDiff(long time) {
		return getFriendlyTimeDiff2(time, new Date().getTime());
	}

	public static String getFriendlyTimeDiff2(long time, long timeNow) {
		long diff = timeNow - time;
		String str = "刚刚";
		if (diff > 0) {
			long s = diff / (60 * 1000);
			long h = s / 60;
			long d = h / 24;
			long m = d / 30;
			long y = m / 12;
			if (y > 0) {
				str = DateUtil.format(time, "MM-dd HH:mm");
			} else if (m > 0) {
				str = DateUtil.format(time, "MM-dd HH:mm");
			} else if (d > 0) {
				str = DateUtil.format(time, "MM-dd HH:mm");
			} else if (h > 0) {
				if (h < 1) {
					str = s + "分钟前";
				} else if (h > 2) {
					str = DateUtil.format(time, "MM-dd HH:mm");
				} else {
					str = "1小时前";
				}
			} else if (s > 0) {
				str = s + "分钟前";
			} else {
				str = "刚刚";
			}
		}

		return str;
	}

	public static String getFriendlyTimeDiff(long time, long timeNow) {
		long diff = timeNow - time;
		String str = "刚刚";
		if (diff > 0) {
			long s = diff / (60 * 1000);
			long h = s / 60;
			long d = h / 24;
			long m = d / 30;
			long y = m / 12;
			if (y > 0) {
				if (y == 1)
					str = "去年";
				else if (y == 2)
					str = "前年";
				else
					str = y + "年前";
			} else if (m > 0) {
				str = m + "月前";
			} else if (d > 0) {
				if (d == 1)
					str = "昨天";
				else if (d == 2)
					str = "前天";
				else
					str = d + "天前";
			} else if (h > 0) {
				str = h + "小时前";
			} else if (s > 0) {
				str = s + "分钟前";
			} else {
				str = "刚刚";
			}
		}

		return str;
	}

	public static void openUrl(String url, Context context) {
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		context.startActivity(intent);
	}

	private static StringBuffer timeBuffer;

	/**
	 * 00 : 00 : 00
	 * 
	 * @return
	 */
	public static String getTimeLengthString(int timeLength) {
		if (timeLength > 0) {
			timeBuffer = new StringBuffer();
			Integer m = timeLength / 60;
			Integer s = timeLength % 60;
			timeBuffer.append("00 : ");
			if (m < 10) {
				timeBuffer.append("0" + m);
			} else {
				timeBuffer.append(m);
			}
			timeBuffer.append(" : ");
			if (s < 10) {
				timeBuffer.append("0" + s);
			} else {
				timeBuffer.append(s);
			}
			return timeBuffer.toString();
		}
		return "00:00";
	}

	public static String hashKeyForDisk(String key) {
		String cacheKey;
		try {
			final MessageDigest mDigest = MessageDigest.getInstance("MD5");
			mDigest.update(key.getBytes());
			cacheKey = bytesToHexString(mDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			cacheKey = String.valueOf(key.hashCode());
		}
		return cacheKey;
	}

	private static String bytesToHexString(byte[] bytes) {
		// http://stackoverflow.com/questions/332079
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(0xFF & bytes[i]);
			if (hex.length() == 1) {
				sb.append('0');
			}
			sb.append(hex);
		}
		return sb.toString();
	}

	public static byte[] readFile(String pathStr) {
		InputStream is = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int n;
		try {
			is = new FileInputStream(pathStr);// pathStr 文件路径
			while ((n = is.read(b)) != -1) {
				out.write(b, 0, n);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return out.toByteArray();
	}

	public static String readFileToString(InputStream is) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int n;
		try {
			while ((n = is.read(b)) != -1) {
				out.write(b, 0, n);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return out.toString();
	}

	private static AlertDialog progressDialogLoading;

	public static void showProgressDialog() {
		if (progressDialogLoading != null && !progressDialogLoading.isShowing()) {
			progressDialogLoading.show();
		}
	}

	public static void dismissProgressDialog() {
		if (progressDialogLoading != null && progressDialogLoading.isShowing()) {
			progressDialogLoading.dismiss();
		}
	}


	public static void saveNetworkSetting(Context c, boolean tag) {
		putSharePreference(c, "network_setting", "network_2g_3g", tag);
	}

	public static void saveNetworkUploadSetting(Context c, boolean tag) {
		putSharePreference(c, "network_setting", "network_2g_3g_uploading", tag);
	}

	public static boolean getNetworkSetting(Context c) {
		return getSharePreferenceBoolean(c, "network_setting", "network_2g_3g");
	}

	public static boolean getNetworkUploadSetting(Context c) {
		return getSharePreferenceBoolean(c, "network_setting", "network_2g_3g_uploading");
	}

	public static void startActivity(Context packageContext, Class<?> cls, Bundle bundle) {
		Intent it = new Intent();
		it.setClass(packageContext, cls);
		if (bundle != null) {
			it.putExtras(bundle);
		}
		packageContext.startActivity(it);
		((Activity) packageContext).overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public static void startActivity(Context packageContext, Class<?> cls) {
		startActivity(packageContext, cls, null);
	}
	
	public static String formatDate(Date date){
		if (date == null)
			return "";
		
		StringBuffer sb = new StringBuffer();
		long duration = System.currentTimeMillis() - date.getTime();
		if (duration > DateUtil.MILLIS_PER_DAY) {
			sb.append(duration / DateUtil.MILLIS_PER_DAY).append("天前");
		} else if (duration > DateUtil.MILLIS_PER_HOUR) {
			sb.append(duration / DateUtil.MILLIS_PER_HOUR).append("小时前");
		} else if (duration > DateUtil.MILLIS_PER_DAY) {
			sb.append(duration / DateUtil.MILLIS_PER_DAY).append("分钟前");
		} else {
			sb.append("1分钟前");
		}
		return sb.toString();
	}

//	public static Bitmap getMiniVideoBitmapByGuid(String guid) {
//		return guid != null ? ThumbnailUtils.createVideoThumbnail(getFileNamebyGuid(guid), Thumbnails.MINI_KIND) : null;
//	}
//
//	public static Drawable getDefaultBigPic(Context context) {
//		return context.getResources().getDrawable(R.drawable.head_big);
//	}
//
//	private static Bitmap b;
//
//	public static Bitmap getDefaultBigBitmap(Context context) {
//		if (b == null) {
//			b = ((BitmapDrawable) context.getResources().getDrawable(R.drawable.head_big)).getBitmap();
//		}
//
//		return b;
//	}

	
}
